import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  FlatList, 
  TextInput, 
  Button, 
  StyleSheet, 
  KeyboardAvoidingView, 
  Platform, 
  ActivityIndicator,
  TouchableOpacity 
} from 'react-native';
import { FontAwesome } from '@expo/vector-icons';
import { useChat } from '../contexts/ChatContext';
import EmotionAnalysis from '../components/EmotionAnalysis';

const ChatScreen = () => {
  const { 
    messages, 
    isLoading, 
    error, 
    sendMessage, 
    userEmotion 
  } = useChat();
  
  const [inputText, setInputText] = useState('');
  
  // 滚动到最新消息
  const flatListRef = React.useRef();
  
  useEffect(() => {
    if (flatListRef.current) {
      flatListRef.current.scrollToEnd({ animated: true });
    }
  }, [messages]);
  
  const handleSend = () => {
    if (inputText.trim()) {
      sendMessage(inputText);
      setInputText('');
    }
  };
  
  const renderMessage = ({ item }) => {
    const isUser = item.sender === 'user';
    const bgColor = isUser ? '#4F46E5' : '#FFFFFF';
    const textColor = isUser ? '#FFFFFF' : '#1F2937';
    const alignSelf = isUser ? 'flex-end' : 'flex-start';
    
    return (
      <View style={[styles.messageContainer, { alignSelf }]}>
        <View style={[styles.messageBubble, { backgroundColor: bgColor }]}>
          <Text style={[styles.messageText, { color: textColor }]}>
            {item.text}
          </Text>
          {!isUser && item.emotion && (
            <View style={styles.emotionIndicator}>
              <FontAwesome 
                name={getEmotionIcon(item.emotion)} 
                size={16} 
                color={getEmotionColor(item.emotion)} 
              />
              <Text style={[
                styles.emotionText, 
                { color: getEmotionColor(item.emotion) }
              ]}>
                {getEmotionLabel(item.emotion)}
              </Text>
            </View>
          )}
        </View>
        <Text style={styles.messageTime}>
          {new Date().toLocaleTimeString()}
        </Text>
      </View>
    );
  };
  
  return (
    <KeyboardAvoidingView 
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={styles.header}>
        <View style={styles.emotionStatus}>
          <FontAwesome 
            name={getEmotionIcon(userEmotion)} 
            size={20} 
            color={getEmotionColor(userEmotion)} 
          />
          <Text style={styles.emotionStatusText}>
            {getEmotionLabel(userEmotion)}
          </Text>
        </View>
        <Text style={styles.headerTitle}>AI情感聊天助手</Text>
        <TouchableOpacity>
          <FontAwesome name="info-circle" size={20} color="#6B7280" />
        </TouchableOpacity>
      </View>
      
      <FlatList
        ref={flatListRef}
        data={messages}
        renderItem={renderMessage}
        keyExtractor={(item, index) => index.toString()}
        contentContainerStyle={styles.messagesContainer}
        style={styles.flatList}
      />
      
      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}
      
      {isLoading && (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="small" color="#4F46E5" />
          <Text style={styles.loadingText}>思考中...</Text>
        </View>
      )}
      
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.inputField}
          placeholder="输入消息..."
          value={inputText}
          onChangeText={setInputText}
          multiline={true}
          onSubmitEditing={handleSend}
          placeholderTextColor="#9CA3AF"
        />
        <TouchableOpacity 
          style={styles.sendButton}
          onPress={handleSend}
          disabled={!inputText.trim()}
        >
          <FontAwesome 
            name="paper-plane" 
            size={20} 
            color={inputText.trim() ? '#FFFFFF' : '#9CA3AF'}
          />
        </TouchableOpacity>
      </View>
      
      {inputText.trim().length > 0 && (
        <EmotionAnalysis message={inputText} />
      )}
    </KeyboardAvoidingView>
  );
};

// 情感辅助函数
const getEmotionIcon = (emotion) => {
  switch(emotion) {
    case 'positive':
      return 'smile-o';
    case 'negative':
      return 'frown-o';
    case 'excited':
      return 'bolt';
    case 'sad':
      return 'cry';
    case 'angry':
      return 'angry';
    default:
      return 'meh-o';
  }
};

const getEmotionColor = (emotion) => {
  switch(emotion) {
    case 'positive':
      return '#10B981'; // 绿色
    case 'negative':
      return '#EF4444'; // 红色
    case 'excited':
      return '#F59E0B'; // 橙色
    case 'sad':
      return '#3B82F6'; // 蓝色
    case 'angry':
      return '#DC2626'; // 深红色
    default:
      return '#6B7280'; // 灰色
  }
};

const getEmotionLabel = (emotion) => {
  switch(emotion) {
    case 'positive':
      return '积极';
    case 'negative':
      return '消极';
    case 'excited':
      return '兴奋';
    case 'sad':
      return '悲伤';
    case 'angry':
      return '愤怒';
    default:
      return '中性';
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9FAFB'
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#1F2937'
  },
  emotionStatus: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  emotionStatusText: {
    marginLeft: 8,
    fontSize: 14,
    color: '#4B5563'
  },
  messagesContainer: {
    padding: 16,
    paddingBottom: 8
  },
  messageContainer: {
    marginBottom: 16,
    maxWidth: '80%'
  },
  messageBubble: {
    borderRadius: 16,
    padding: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2
  },
  messageText: {
    fontSize: 16
  },
  messageTime: {
    fontSize: 10,
    color: '#9CA3AF',
    marginTop: 4,
    marginLeft: 8
  },
  emotionIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8
  },
  emotionText: {
    marginLeft: 4,
    fontSize: 12
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: 16,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB'
  },
  inputField: {
    flex: 1,
    marginRight: 12,
    padding: 12,
    borderWidth: 1,
    borderColor: '#E5E7EB',
    borderRadius: 24,
    fontSize: 16,
    backgroundColor: '#F9FAFB'
  },
  sendButton: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: inputText.trim() ? '#4F46E5' : '#E5E7EB',
    justifyContent: 'center',
    alignItems: 'center'
  },
  errorContainer: {
    padding: 12,
    backgroundColor: '#FEE2E2',
    margin: 16,
    borderRadius: 8
  },
  errorText: {
    color: '#DC2626',
    textAlign: 'center'
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    justifyContent: 'center'
  },
  loadingText: {
    marginLeft: 8,
    color: '#6B7280'
  }
});

export default ChatScreen;    